<template>
  <el-card class="page_card">
    <el-form :inline="true" class="form">
      <el-form-item label="类别名称：">
        <el-input v-model="data.keyword" placeholder="请输入类别名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" color="#626aef" @click="search" 
          :disabled="data.keyword?false:true">搜索</el-button>
        <el-button @click="reset" color="#626aef" plain>重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="Plus" @click="addJg">添加类别</el-button>
    <el-table border :data="data.categoryTableData" row-key="id" :height="710">
      <el-table-column label="序号" align="center" prop="order" :width="150"></el-table-column>
      <el-table-column label="类别名称" align="center" prop="name"></el-table-column>
      <el-table-column label="操作" width="270px" align="left" header-align="center">
        <template #="{row}">
          <el-button type="primary" link icon="Edit" @click="updateMenu(row)">编辑</el-button>
          <el-button type="primary" link icon="Plus" @click="addJgRow(row)" v-if="row.parentId==0">添加</el-button>
          <el-popconfirm :title="`确认删除${row.name}吗？`" width="240px" 
            @confirm="deleteJg(row)" v-if="row.children.length==0">
            <template #reference>
              <el-button type="danger" link icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 添加类别、更新类别 -->
  <el-dialog v-model="data.addCategoryDialog" :title="data.categoryForm.id?'更新类别':'添加类别'" width="650">
    <el-form :model="data.categoryForm" :rules="data.rules" ref="formRef" label-width="130px" style="max-width: 550px">
      <el-form-item label="上级节点" prop="parentId">
        <el-select v-model="data.categoryForm.parentId" placeholder="请选择上级节点" >
          <el-option label="根节点" :value="0"/>
          <el-option v-for="item in data.parentIdList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="类别名称" prop="categoryName">
        <el-input v-model="data.categoryForm.categoryName" placeholder="请输入类别名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref,onMounted,reactive,nextTick} from 'vue'
import {reqCategoryTreeData,reqAddOrUpdateCategory,reqRemoveCategory} from '@/api/case/categoryApi'
import type { Category,CategoryResData } from '@/api/case/categoryType'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '@/store/modules/setting'
let settingStore = useLayOutSettingStore() // 模板setting仓库
let formRef = ref<any>() //form表单实例
const data = reactive({
  keyword:'',
  categoryTableData:[] as Category[],
  addCategoryDialog:false, //新增对话框
  categoryForm:{ //新增表单
    parentId:0,
    categoryName:'', 
    id:'',
  },
  parentIdList:[] as Category[], //上级节点下拉框
  rules:{
    categoryName:[{ required: true, trigger: 'blur', message:'请输入类别项名称'}],
  }
})

onMounted(() => {
  initTableData()
})

// 搜索
const search = ()=>{
  initTableData(data.keyword)
}
// 重置
const reset = ()=>{
  settingStore.refsh = !settingStore.refsh
}
// 获取类别列表
const initTableData = async(categoryName='')=> {
  let res:CategoryResData = await reqCategoryTreeData(categoryName)
  if(res.code==200){
    data.categoryTableData = generateOrder(res.data)
    data.parentIdList = res.data.filter((item:any) => {
      return item.parentId == 0
    })
  }
}
// 递归生成当前项order字段
const generateOrder = (tree: any[], parentOrder = '') => {
  return tree.map((item, parentIndex) => {
    const order = `${parentOrder ? parentOrder + '.' : ''}${parentIndex + 1}`
    item.order = order
    // 递归处理子项
    if (item.children && item.children.length > 0) {
      item.children = generateOrder(item.children, order)
    } else {
      item.children = []
    }
    return item
  })
}
// 新增对话框
const addJg = ()=> {
  data.addCategoryDialog = true
  // 清空数据
  Object.assign(data.categoryForm,{
    parentId:0,
    categoryName:'', 
    id:'',
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('categoryName')
  })
}
// 编辑对话框
const updateMenu = (row:Category)=> {
  data.addCategoryDialog = true
  Object.assign(data.categoryForm,row)
  data.categoryForm.categoryName = row.name
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('categoryName')
  })
}
// 新增/编辑确认
const save = async() => {
  try{
    await formRef.value.validate()
    let res = await reqAddOrUpdateCategory(data.categoryForm)
    if(res.code==200){
      data.addCategoryDialog = false
      ElMessage.success(data.categoryForm.id?'更新成功！':'添加成功！')
      initTableData()
    }else{
      data.addCategoryDialog = false
      ElMessage.error(data.categoryForm.id?'更新失败！':'添加失败！')
    }
  }catch (error) {}
}
const cancel = ()=>{
  data.addCategoryDialog = false
}

// 行数据 添加类别
const addJgRow = async(row:Category)=> {
  data.addCategoryDialog = true
  // 清空数据
  Object.assign(data.categoryForm,{
    parentId:row.id,
    categoryName:'',  
    id:'',
  })
  nextTick(() => {
    // 清除上一次错误提示信息
    formRef.value.clearValidate('categoryName')
  })
}

// 删除单行类别
const deleteJg = async(row:Category)=>{
  let res = await reqRemoveCategory((row.id as number),row.version)
  if(res.code==200){
    ElMessage.success('删除成功！')
    initTableData()
  }else{
    ElMessage.error('删除失败！')
  }
}
</script>

<style scoped lang="scss">

</style>


